const mongoose = require("mongoose");
const _ = require("lodash")

//新增子类型
const add = async ({ name, count, price, childId, isAttend, desc, image }) => {
    // 获取商品数据模型
    const commsModel = mongoose.model("comms");
    // 创建商品
    const data = await commsModel.create({ name, count, price, childId, isAttend, desc, image, poster: [] })
    // 查找添加的商品
    const comm = await commsModel.findOne({ _id: data._id });
    let status = true;
    // 返回状态值判断是否添加成功
    if (comm) {
        return { status, comm };
    } else {
        status = false;
        return status;
    }

};


// 获取服务端传到数据库的数据{curPage,eachPage}
const getAll = async ({ curPage, eachPage, childId }) => {
    curPage = ~~curPage;
    eachPage = ~~eachPage;
    const data = {
        total: 0,
        maxPage: 0,
        rows: [],
    }

    // 通过model方法获取模型 一个参数获取 三个参数创建
    const commsModel = mongoose.model("comms");
    // 获取当前model映射的集合里面存在的文档总数
    data.total = await commsModel.countDocuments();
    data.maxPage = Math.ceil(data.total / eachPage);
    // commsModel.find() 查询所有数据
    // commsModel.findOne() 查询一条数据，括号内是回调条件
    // skip() 跳过多少行 参数是从第几行跳过
    // limit()查多少条  execut执行
    // populate() 填充
    const skipNum = (curPage - 1) * eachPage;
    data.rows = await commsModel.find().skip(skipNum).limit(eachPage).sort({ name: 1 }).exec();
    if (childId) {
        data.rows = await commsModel.find({ childId }).skip(skipNum).limit(eachPage).sort({ name: 1 }).exec();
    } else {
        data.rows = await commsModel.find().skip(skipNum).limit(eachPage).sort({ name: 1 }).exec();
    }
    // console.log(data);
    return data;
}

// 获取_id对应的父类型
const getOne = async (_id) => {
    const commsModel = mongoose.model("comms");
    const secondKillModel = mongoose.model("secondKill");
    const comm = await commsModel.findOne({ _id });
    if (comm.isAttend) {
        const result = await secondKillModel.findOne({ CommId: _id })
        const data = {
            image: comm.image,
            poster: comm.poster,
            _id: comm._id,
            name: comm.name,
            count: comm.count,
            price: comm.price,
            childId: comm.childId,
            isAttend: comm.isAttend,
            desc: comm.desc, 
            Sale: Number((comm.price * result.Sale).toFixed(2)), 
            Time: result.Time, 
            limit: result.limit
        }
        // comm["Sale"]=comm.price*result.Sale
        // comm["Time"]=result.Time
        // comm["limit"]=result.limit
        console.log(data);
        return data
    } else {
        return comm
    }
};

// 删除id对应子类型
const del = async ({ _id }) => {
    const commsModel = mongoose.model("comms");
    await commsModel.findOneAndDelete({ _id });
    const result = true;
    return result
};

// 修改id对应子类型
const reset = async ({ _id, childId, name, count, price, desc }) => {
    const commsModel = mongoose.model("comms");
    await commsModel.findByIdAndUpdate({ _id }, { childId, name, count, price, desc });
    const result = true;
    return result
};

// update做修改 query查询条件  params需要修改的数据
const update = async (query, params) => {
    console.log(query, params);
    const commsModel = mongoose.model("comms");
    const data = await commsModel.findOne(query);
    if (params.poster) {
        params.poster = [...data.poster, params.poster]
    } else {
        params.image = [...data.image, params.image]
    }
    // updateOne更新符合条件的第一个文档
    await commsModel.updateOne(query, params);
    const result = true
    return result
}

// 获取服务端传到数据库的数据{curPage,eachPage}
const getComms = async () => {
    const commsModel = mongoose.model("comms");
    const data = await commsModel.find();
    // console.log(data);
    return data;
}

// 删除数据 第一步删除浏览器数据 第二步删除后台数据 删除图片
const delImg = async ({ _id, url }) => {
    const commsModel = mongoose.model("comms");
    const comm = await commsModel.findOne({ _id });//拿到
    const newImage = comm.image.splice(comm.image.findIndex(item => item === url), 1)
    await commsModel.updateOne({ _id }, { image: newImage })
    const data = true;
    return data; //删除的数据更新到数据库
}
// 删除海报对应的数据
const delPoster = async ({ _id, url }) => {
    const commsModel = mongoose.model("comms");
    const comm = await commsModel.findOne({ _id });//拿到
    const newPoster = comm.poster.splice(comm.poster.findIndex(item => item === url), 1)
    await commsModel.updateOne({ _id }, { poster: newPoster })
    const data = true;
    return data;  //删除的数据更新到数据库
}

// 获取父类型对应的子类型及商品
const getByParentId = async ({ parentId }) => {
    const commsModel = mongoose.model("comms");
    const labelsModel = mongoose.model("labels");
    const data = await labelsModel.find({ parentId });
    const result = Promise.all(data.map(async (item, index) => {
        const comms = await commsModel.find({ childId: item._id })
        return {
            id: index + 1,
            _id: item._id,
            title: item.title,
            rows: comms
        }
    })).then(res => res)
    return result
}

module.exports = { add, getAll, getOne, del, reset, update, getComms, delPoster, delImg, getByParentId }